package org.devgframwork.datasync.admin.support.init.schedule;

import org.devgframwork.datasync.core.entity.ScheduleConfig;
import org.devgframwork.datasync.core.support.config.SysConfig;
import org.devgframwork.datasync.core.support.service.ScheduleConfigService;
import org.devgframwork.datasync.core.utils.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.List;
import java.util.concurrent.Executors;

@Slf4j
@EnableScheduling
@Configuration
public class ScheduleConfigInit implements SchedulingConfigurer {

    @Autowired
    private SysConfig sysConfig;

    @Autowired
    private ScheduleConfigService scheduleConfigService;

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        List<ScheduleConfig> list = scheduleConfigService.getScheduleConfigList();
        if (CommonUtil.isEmpty(list)) {
            log.info("ScheduleConfigList is null");
            return;
        }
        scheduleConfigService.updateRunning();
        Integer corePoolSize = sysConfig.getSchedule().getPoolSize();
        scheduledTaskRegistrar.setScheduler(Executors.newScheduledThreadPool(corePoolSize));
        for (ScheduleConfig scheduleConfig : list) {
            if (null == scheduleConfig || scheduleConfig.getIsDelete().equals(1)) {
                continue;
            }
            Runnable scheduleRunnable = new ScheduleRunnable(scheduleConfig, scheduleConfigService);
            Trigger scheduleTrigger = new ScheduleTrigger(scheduleConfig, scheduleConfigService);
            scheduledTaskRegistrar.addTriggerTask(scheduleRunnable, scheduleTrigger);
        }
    }
}
